//
//  QSSignInViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/20.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSSignInViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "QSSendRemarkViewController.h"
#import <MapKit/MapKit.h>
#import "BRPickerView.h"
#import "TYAlertController.h"
#import "QSSingInInterface.h"
#import "QSCompayAnotation.h"
#import "CLLocation+Sino.h"
#import "QSOtherSelectCompanyViewController.h"
@interface QSSignInViewController ()<MKMapViewDelegate, CLLocationManagerDelegate,UIPickerViewDelegate, UIPickerViewDataSource>
/**签到Button*/
@property (nonatomic, strong)UIButton *signInButton;
/**签到Label*/
@property (nonatomic, strong)UILabel *signInLabel;
/**当前公司Button*/
@property (nonatomic, strong)UIButton *enterpriseButton;
/** 右侧下拉按钮*/
@property (nonatomic, strong)UIButton *rigntArrowImageView;
/**当前公司Label*/
@property (nonatomic, strong)UILabel *enterpriseLabel;
/**灰分割线*/
@property (nonatomic, strong)UIView *topGrayView;
/**地理位置 Label */
@property (nonatomic, strong)UILabel *locationLabel;
/** 状态imageview*/
@property (nonatomic, strong)UIImageView *stateImageVIew;
/**提醒label*/
@property (nonatomic, strong)UILabel *tipsLabel;
/** 规则Button*/
@property (nonatomic, strong)UIButton *rulesButton;
/**地图view*/
@property (nonatomic, strong)MKMapView *mapView;
/** 定位管理器*/
@property (nonatomic, strong)CLLocationManager *manager;

@property (nonatomic) CLLocationCoordinate2D centerCoordinate;
/** 未绑定视图*/
@property (nonatomic, strong)UIImageView *unboundedImageView;

/** 未绑定Button*/
@property (nonatomic, strong)UILabel *unboundedLabel;
//公司数组
//@property (nonatomic, strong)NSArray *companyArray;
//picker
@property (nonatomic, strong) UIPickerView *areaPickerView;
//取消按钮
@property (nonatomic, strong)UIButton *cancleButton;
//完成按钮
@property (nonatomic, strong)UIButton *sureButton;
//头部视图
@property (nonatomic, strong)UIView *alertBackgroundView;
//选中的公司id
@property (nonatomic, strong)NSString *selectId;
//签到的地址
@property (nonatomic, strong)NSString *signAddress;
//选中公司的范围
@property (nonatomic, strong)NSNumber *round;

@property (nonatomic, strong) QSCompayAnotation *compayAnotation;
@property (nonatomic, assign) NSInteger selectedPickerIndex;
@property (nonatomic, assign) BOOL hasSetCenter;


@property (nonatomic, strong)QSVisitInfoCompanyListModel *companyModel;
@end
//static NSString *kCompanyKey = @"companyKey";
//static NSString *kCompanyName = @"companyName";
//static NSString *kCompanyRound = @"round";
@implementation QSSignInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    if (!self.companyModelList ||self.companyModelList.count == 0 || kCurrentUser.enterpriseLevel.integerValue == 4) {
//        [self configUnboundedView];
//    }else{
//    }
    [self configSubView];
    [self configLocationManager];
    [self setDefautCompany];//设置默认
//    [self updateLoactionLabel];
    [self addCompanyAnnotation];
}

- (void)updateLoactionLabel {
  //根据经纬度解析成位置
  if (self.hasSetCoordinate) {
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    CLLocation *companyLocation = [[CLLocation alloc] initWithLatitude:self.currentCompanyEarchCoordinate.latitude longitude:self.currentCompanyEarchCoordinate.longitude];
    [geocoder reverseGeocodeLocation:companyLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *mark = [placemarks objectAtIndex:0];
        if (!error) {
            NSLog(@"city %@ subcity %@",mark.subLocality,mark.thoroughfare);
            self.locationLabel.text = [NSString stringWithFormat:@"%@, %@", mark.subLocality ?: @"", mark.thoroughfare ?: @""];
        } else {
            self.locationLabel.text = @"获取企业地区失败";
        }
    }];
  } else {
    self.locationLabel.text = @"当前企业未设置签到经纬度";
  }
}

- (void)addCompanyAnnotation {
  [self.mapView removeAnnotation:self.compayAnotation];

  if (self.hasSetCoordinate) {
    [self.compayAnotation setCoordinate:self.currentCompanyEarchCoordinate];
    [self.mapView addAnnotation:self.compayAnotation];
    [self.mapView setCenterCoordinate:self.compayAnotation.coordinate];
  } else {
    [self.mapView setCenterCoordinate:self.centerCoordinate];
  }
}

//配置定位
- (void)configLocationManager{
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0 ) {
        [_manager requestAlwaysAuthorization];
    }
    if ([CLLocationManager locationServicesEnabled]) {
        _manager = [[CLLocationManager alloc] init];
        [_manager requestAlwaysAuthorization];
        _manager.delegate = self;
        [_manager startUpdatingLocation];
    }
}

- (void)configAndShowPicker{
    self.areaPickerView =[[UIPickerView alloc]init];
    self.areaPickerView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    [self.alertBackgroundView addSubview: self.areaPickerView];
    [self.areaPickerView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.equalTo(self.alertBackgroundView);
         make.top.equalTo(self.alertBackgroundView.mas_top).offset(50);
         make.bottom.equalTo(self.alertBackgroundView);
         make.width.offset(kScreenWidth);
    }];
    
    [self.alertBackgroundView addSubview:self.cancleButton];
    [self.alertBackgroundView addSubview:self.sureButton];
    [self.cancleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.alertBackgroundView);
        make.top.equalTo(self.alertBackgroundView);
        make.width.offset(kRealValue(64));
        make.height.offset(kRealValue(40));
    }];
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.alertBackgroundView);
        make.top.equalTo(self.alertBackgroundView);
        make.width.offset(kRealValue(64));
        make.height.offset(kRealValue(40));
    }];
    
    self.areaPickerView.delegate=self;
    self.areaPickerView.dataSource=self;
    
    [self.areaPickerView selectRow:0 inComponent:0 animated:YES];
     self.areaPickerView.showsSelectionIndicator=YES;
    TYAlertController *alertVC = [TYAlertController alertControllerWithAlertView:self.alertBackgroundView preferredStyle:TYAlertControllerStyleActionSheet transitionAnimation:TYAlertTransitionAnimationScaleFade];
    alertVC.backgoundTapDismissEnable = YES;
    [self presentViewController:alertVC animated:YES completion:^{
        
    }];
        
}


//默认选中第一行 取出坐标id
- (void)setDefautCompany{
     [self.enterpriseButton setTitle:@"点击搜索企业" forState:UIControlStateNormal];
    self.locationLabel.text = @"暂无企业位置信息";
//    if (self.companyModelList.count > 0) {
//        //默认选中第一行第一列
//        QSVisitInfoCompanyListModel *model = self.companyModelList.firstObject;
//        self.selectId = model.companyKey;//默认从0选中
//        self.round = @(model.round.floatValue);//默认选中范围
//        //默认显示的公司
//        ;
//        [self.enterpriseButton setTitle:[NSString stringWithFormat:@"%@", model.companyName] forState:UIControlStateNormal];
//    }else{
//        [self.enterpriseButton setTitle:@"点击搜索" forState:UIControlStateNormal];
//    }
}
- (void)configUnboundedView{
    [self.view addSubview:self.unboundedImageView];
    [self.view addSubview:self.unboundedLabel];
    [_unboundedImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(- kRealValue(64));
        make.width.offset(kRealValue(181));
        make.height.offset(kRealValue(135));
    }];
    [_unboundedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_unboundedImageView.mas_bottom).offset(kRealValue(16));
    }];
}




- (void)configSubView{
    self.view.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    [self.view addSubview:self.enterpriseLabel];
    [self.view addSubview:self.enterpriseButton];
    [self.view addSubview:self.rigntArrowImageView];
    [self.view addSubview:self.topGrayView];
    [self.view addSubview:self.locationLabel];
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.signInButton];
    [self.view addSubview:self.signInLabel];
    [self.view addSubview:self.stateImageVIew];
    [self.view addSubview:self.tipsLabel];
    [self.view addSubview:self.rulesButton];
    [_enterpriseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(11));
        make.top.equalTo(self.view).offset(kRealValue(14));
        make.width.offset(kRealValue(100));
    }];
    [_rigntArrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kRealValue(11));
        make.centerY.equalTo(_enterpriseLabel);
        make.size.mas_equalTo(CGSizeMake(kRealValue(9), kRealValue(6)));
    }];
    [_enterpriseButton mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.equalTo(_enterpriseLabel.mas_right).offset(kRealValue(0));
      make.centerY.equalTo(_enterpriseLabel);
      make.height.offset(kRealValue(15));
      make.right.equalTo(_rigntArrowImageView.mas_left).offset(-kRealValue(5));
    }];
    [_topGrayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_enterpriseButton.mas_bottom).offset(kRealValue(15));
        make.left.equalTo(self.view).offset(kRealValue(11));
        make.right.equalTo(self.view).offset(- kRealValue(11));
        make.height.offset(0.5);
    }];
    [_locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topGrayView.mas_bottom).offset(kRealValue(15));
        make.left.equalTo(self.view).offset(kRealValue(11));
        make.right.equalTo(self.view).offset(-kRealValue(11));
    }];
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_locationLabel.mas_bottom).offset(kRealValue(9.5));
        make.left.equalTo(self.view).offset(kRealValue(11));
        make.right.equalTo(self.view).offset(- kRealValue(11));
        make.height.offset(kRealValue(200));
    }];
    [_signInButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_mapView.mas_bottom).offset(kRealValue(24));
        make.width.height.offset(kRealValue(187));
    }];
    [_signInLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_signInButton);
        make.centerY.equalTo(_signInButton).offset(- kRealValue(10));
    }];
    [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_signInButton);
        if (kDevice_Is_iPhoneX) {
             make.top.equalTo(_signInButton.mas_bottom).offset(kRealValue(0));
        }else{
            make.top.equalTo(_signInButton.mas_bottom).offset(kRealValue(- 10));
        }
    }];
    [_stateImageVIew mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_tipsLabel.mas_left).offset(- kRealValue(5));
        make.centerY.equalTo(_tipsLabel);
    }];
    [_rulesButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_tipsLabel);
        make.top.equalTo(_tipsLabel.mas_bottom).offset(kRealValue(10));
    }];
}

#pragma mark - 懒加载
- (UIImageView *)unboundedImageView{
    if (!_unboundedImageView) {
        _unboundedImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_unbounded"]];
    }
    return _unboundedImageView;
}
- (UILabel *)unboundedLabel{
    if (!_unboundedLabel) {
        _unboundedLabel = [UILabel labelWithName:@"对不起，您暂未绑定服务企业" font:[UIFont QSFontOfSize16] textColor:[UIColor QSColorBlack666666] textAlignment:NSTextAlignmentCenter];
    }
    return _unboundedLabel;
}


- (UIButton *)signInButton{
    if (!_signInButton) {
        _signInButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
        _signInButton.userInteractionEnabled = NO;
        [_signInButton setButtonTopImage:_signInButton];
        [_signInButton addTarget:self action:@selector(signInAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _signInButton;
}

- (UILabel *)signInLabel{
    if (!_signInLabel) {
        _signInLabel = [UILabel labelWithName:@"签到" font:[UIFont QSFontOfSize18] textColor:[UIColor QSColorWhiteFFFFFF] textAlignment:NSTextAlignmentCenter];
    }
    return _signInLabel;
}

-(UILabel *)enterpriseLabel{
    if (!_enterpriseLabel) {
        _enterpriseLabel = [UILabel labelWithName:@"当前签到企业:" font:[UIFont QSFontOfSize13] textColor:[UIColor QSColorBlack666666] textAlignment:NSTextAlignmentLeft];
        _enterpriseLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectAction:)];
        [_enterpriseLabel addGestureRecognizer:tap];
    }
    return _enterpriseLabel;
}

-(UIButton *)enterpriseButton{
    if (!_enterpriseButton) {
        _enterpriseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _enterpriseButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
      //        [_enterpriseButton setImage:[UIImage imageNamed:@"ic_selectpeople"] forState:UIControlStateNormal];
        _enterpriseButton.titleLabel.font = [UIFont QSFontOfSize14];
        _enterpriseButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_enterpriseButton setTitleColor:[UIColor QSColorBlack434343] forState:UIControlStateNormal];
        [_enterpriseButton addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _enterpriseButton;
}

- (UIButton *)rigntArrowImageView{
    if (!_rigntArrowImageView) {
        _rigntArrowImageView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rigntArrowImageView setImage:[UIImage imageNamed:@"ic_selectpeople"] forState:UIControlStateNormal];
        [_rigntArrowImageView addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
//        _rigntArrowImageView = [[UIButton alloc]initWithImage:[UIImage imageNamed:@"ic_selectpeople"]];
//        _rigntArrowImageView.userInteractionEnabled = YES;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectAction:)];
//        [_rigntArrowImageView addGestureRecognizer:tap];
        
        
    }
    return _rigntArrowImageView;
}

- (UIView *)topGrayView{
    if (!_topGrayView) {
        _topGrayView = [[UIView alloc]init];
        _topGrayView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    }
    return _topGrayView;
}
- (UILabel *)locationLabel{
    if (!_locationLabel) {
        _locationLabel = [UILabel labelWithName:@"" font:[UIFont QSFontOfSize16] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentLeft];
        _locationLabel.numberOfLines = 2;
    }
    return _locationLabel;
}


- (UIImageView *)stateImageVIew{
    if (!_stateImageVIew) {
        _stateImageVIew = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"ic_state_no"]];
    }
    return _stateImageVIew;
}

- (UILabel *)tipsLabel{
    if (!_tipsLabel) {
        _tipsLabel = [UILabel labelWithName:@"" font:[UIFont QSFontOfSize12] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentLeft];
    }
    return _tipsLabel;
}

- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
        _mapView.delegate = self;
        _mapView.mapType = MKMapTypeStandard;
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    }
    return _mapView;
}


- (UIButton *)cancleButton{
    if (!_cancleButton) {
        _cancleButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cancleButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancleButton addTarget:self action:@selector(handleCancle) forControlEvents:UIControlEventTouchUpInside];
        [_cancleButton becomeFirstResponder];
    }
    return _cancleButton;
}

- (UIButton *)sureButton{
    if (!_sureButton) {
        _sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_sureButton setTitle:@"完成" forState:UIControlStateNormal];
        [_sureButton addTarget:self action:@selector(handleSure) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureButton;
}

- (UIView *)alertBackgroundView{
    if (!_alertBackgroundView) {
        _alertBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kRealValue(240))];
        _alertBackgroundView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        [self.view addSubview:self.alertBackgroundView];
    }
    return _alertBackgroundView;
}

- (UIButton *)rulesButton{
    if (!_rulesButton) {
        _rulesButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rulesButton setTitle:@"查看规则" forState:UIControlStateNormal];
        [_rulesButton setTitleColor:[UIColor colorWithHexString:@"#777CB3"] forState:UIControlStateNormal];
        _rulesButton.titleLabel.font = [UIFont QSFontOfSize12];
        [_rulesButton addTarget:self action:@selector(handleRulesAction:) forControlEvents:UIControlEventTouchUpInside];
        _rulesButton.hidden = YES;
    }
    return _rulesButton;
}
#pragma mark - Action
- (void)handleRulesAction:(UIButton *)sender{
    [TYAlertController showAlertViewWithTitle:@"签到规则" message:@"在企业位置的1km范围内才可以签到" confirmTitle:@"我知道了"];
}

- (void)signInAction:(UIButton *)sender{
    NSTimeInterval timestamp = [NSDate currentTimestamp];
    NSString *timestampStr = [NSString stringWithFormat:@"%0.f", timestamp];
    NSLog(@"签到key %@, \n 地址：%@\n 时间戳:%@", self.selectId, self.locationLabel.text, timestampStr);
    [QSSingInInterface addSignRecorWithEsCompanyKey:self.selectId EsAdress:self.locationLabel.text EsTime:timestampStr AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            QSSendRemarkViewController *vc = [QSSendRemarkViewController new];
            vc.esId = (NSString *)result;
            vc.companyKey = self.selectId;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [QSAppKeyWindow showAutoHideHudWithText:rspStatusAndMessage.message];
        }
    }];    
}
//选择公司
- (void)selectAction:(UIButton *)sender{
    
//    [self configAndShowPicker];
    QSOtherSelectCompanyViewController *vc = [QSOtherSelectCompanyViewController new];
    WeakSelf(weakSelf);
    vc.didSelectCompanyBlock = ^(QSVisitInfoCompanyListModel *model) {
        self.companyModel = model;
        [self updateLoactionLabel];
        [self addCompanyAnnotation];
        NSString *companyName = model.companyName;
        weakSelf.selectId = model.companyKey;
        weakSelf.round = @(model.round.floatValue) ;//切换取出范围
        [weakSelf.enterpriseButton setTitle:companyName forState:UIControlStateNormal];
        NSNumber *longitude = @(model.longitude.floatValue);
        NSNumber *latitude = @(model.latitude.floatValue);
        if (longitude && latitude) {
            
            [weakSelf CalculationOfDistanceWithLongitude:longitude.doubleValue Latitude:latitude.doubleValue];
        }else{
            weakSelf.signInButton.userInteractionEnabled = NO;
            [weakSelf.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
            [weakSelf.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
            weakSelf.tipsLabel.text = @"您的企业未添加位置";
            weakSelf.rulesButton.hidden = NO;//显示规则
        }
    };
    [self.navigationController pushViewController:vc animated:YES];
}
//取消
- (void)handleCancle{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//完成
- (void)handleSure{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSInteger pIndex = [self.areaPickerView selectedRowInComponent:0];
    
    self.selectedPickerIndex = pIndex;
    [self updateLoactionLabel];
    [self addCompanyAnnotation];
  
    QSVisitInfoCompanyListModel *companyModel = self.companyModelList[pIndex];
    NSString *companyName = companyModel.companyName;
    self.selectId = companyModel.companyKey;
    self.round = @(companyModel.round.floatValue) ;//切换取出范围
    [self.enterpriseButton setTitle:companyName forState:UIControlStateNormal];
    NSNumber *longitude = @(companyModel.longitude.floatValue);
    NSNumber *latitude = @(companyModel.latitude.floatValue);
    if (longitude && latitude) {
        [self CalculationOfDistanceWithLongitude:longitude.doubleValue Latitude:latitude.doubleValue];
    }else{
        self.signInButton.userInteractionEnabled = NO;
        [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
        [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
        self.tipsLabel.text = @"您的企业未添加位置";
        _rulesButton.hidden = NO;//显示规则
    }
}
//计算经纬度和本地的距离 超过200米则置灰按钮
- (void)CalculationOfDistanceWithLongitude:(CLLocationDegrees)longitude
                                  Latitude:(CLLocationDegrees)latitude{
    if (longitude && latitude) {
        CLLocation *currentUserPoint = [[CLLocation alloc]initWithLatitude:self.centerCoordinate.latitude   longitude:self.centerCoordinate.longitude];
        CLLocation *companyPoint = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
  
        CLLocationDistance kilometers = [[currentUserPoint locationMarsFromEarth] distanceFromLocation:companyPoint];
        NSString *strOfDistance = [NSString stringWithFormat:@"%.1f", kilometers];
        NSLog(@"距离公司有%.2f米",strOfDistance.floatValue);
        [self upDateUIWithKilometers:strOfDistance.floatValue];
    }else{
        self.signInButton.userInteractionEnabled = NO;
        [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
        [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
        self.tipsLabel.text = @"当前企业未设置签到经纬度";
        _rulesButton.hidden = NO;
    }
}
//这里更新UI
- (void)upDateUIWithKilometers:(CGFloat)kilometer{
    CGFloat range = [self.round floatValue] *1000;
    if (kilometer > range) {
        [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
        self.signInButton.userInteractionEnabled = NO;
        [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
        self.tipsLabel.text = @"当前未进入相关企业区域";
        
        _rulesButton.hidden = NO;
    }else{
        [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_blue"] forState:UIControlStateNormal];
        self.signInButton.userInteractionEnabled = YES;
        [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_ok"]];
        self.tipsLabel.text = [NSString stringWithFormat:@"已进入企业签到范围"];
        _rulesButton.hidden = YES;
    }
}

#pragma mark - MKMapViewDelagete

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
  MKAnnotationView *annotationView = nil;
  if([annotation isKindOfClass:[QSCompayAnotation class]]) {
    MKAnnotationView * annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation1"];
    if(!annotationView) {
      annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotation1"];
    }
  }
  return annotationView;
}

#pragma mark - CLLocationManagerDelagete
//定位成功
 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
      NSLog(@"定位成功");
      //获取定位的坐标
      CLLocation *location = [locations firstObject];
      //获取坐标
      self.centerCoordinate = location.coordinate;
      NSLog(@"定位的坐标：%f,%f", self.centerCoordinate.longitude, self.centerCoordinate.latitude);
    MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.centerCoordinate, span);
    _mapView.region = region;
    
  //开始比较位置（默认第一个公司）
    QSVisitInfoCompanyListModel *model = self.companyModelList.firstObject;
    NSNumber *longitude = @(model.longitude.floatValue);
    NSNumber *latitude = @(model.latitude.floatValue);
    if (self.hasSetCoordinate) {
        [self CalculationOfDistanceWithLongitude:longitude.doubleValue Latitude:latitude.doubleValue];
    }else{
        self.signInButton.userInteractionEnabled = NO;
        [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
        [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
        self.tipsLabel.text = @"您的企业未添加位置";
    }

    if (self.hasSetCoordinate) {
        [self.mapView setCenterCoordinate:self.currentCompanyMarsCoordinate];
    }
    [_manager stopUpdatingLocation];
}
//定位失败
 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败");
    self.signInButton.userInteractionEnabled = NO;
    [self.stateImageVIew setImage:[UIImage imageNamed:@"ic_state_no"]];
    [self.signInButton setImage:[UIImage imageNamed:@"ic_signin_gray"] forState:UIControlStateNormal];
    self.tipsLabel.text = @"请在设置里允许此App访问您的位置";
    [QSAppKeyWindow showAutoHideHudWithText:@"请在设置里允许此App访问您的位置"];
}

#pragma mark - PickerDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//    NSString *key = @"companyName";
    QSVisitInfoCompanyListModel *model = self.companyModelList[row];
    return model.companyName;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.companyModelList.count;
    
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
 
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.textColor = [UIColor blackColor];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}



- (CLLocationCoordinate2D)currentCompanyMarsCoordinate {
  CLLocation *earthLocation = [[CLLocation alloc] initWithLatitude:self.companyModel.latitude.doubleValue longitude:self.companyModel.longitude.doubleValue];
  CLLocation *marsLocation = [earthLocation locationMarsFromEarth];
  return marsLocation.coordinate;
}

- (CLLocationCoordinate2D)currentCompanyEarchCoordinate {
  return CLLocationCoordinate2DMake(self.companyModel.latitude.doubleValue, self.companyModel.longitude.doubleValue);
}

- (BOOL)hasSetCoordinate {
  return self.companyModel.latitude.length && self.companyModel.longitude.length;
}

- (QSCompayAnotation *)compayAnotation {
  if (!_compayAnotation) {
    _compayAnotation = [[QSCompayAnotation alloc] init];
  }
  return _compayAnotation;
}

@end
